class StorageCache {
  #storage = null
  constructor(isLocal = true) {
    this.#storage = isLocal ? window.localStorage : window.sessionStorage
  }

  set(key, value) {
    const dataType = typeof value
    const dateTime = new Date().getTime()
    const obj = { value, dataType, dateTime }
    this.#storage.setItem(key, JSON.stringify(obj))
  }

  get(key) {
    const result = this.#storage.getItem(key)
    try {
      return result ? JSON.parse(result).value : result
    } catch {
      return result
    }
  }

  getAll() {
    const list = []
    for (let i = 0; i < this.#storage.length; i++) {
      const curKey = this.#storage.key(i)
      list.push({
        key: curKey,
        value: this.getCache(curKey)
      })
    }
    return list
  }

  remove(key) {
    this.#storage.removeItem(key)
  }

  clear() {
    this.#storage.clear()
  }
}

export const sessiconCache = new StorageCache(false)
export const localCache = new StorageCache(true)
